package com.aop.SpElAop.LogAop;

/**
 * @Package: com.aop.SpElAop
 * @ClassName: LogAspect
 * @Author: wulongkai
 * @CreateTime: 2024/7/9 11:06
 * @Description:
 */

import com.aop.SpElAop.ExpressionParser.ValueParser;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
    private final ValueParser valueParser;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.aop.SpElAop.LogAop.Logging)")
    private void pointCut() {
    }

    @Around("pointCut() && @annotation(logging)")
    public Object around(ProceedingJoinPoint point, Logging logging) throws Throwable {
        Object proceed;
        Boolean print = true;
        try {
            proceed = point.proceed();
            if (!StringUtils.isEmpty(logging.condition())) {
                print = valueParser.parse(point, logging::condition, proceed, null, Boolean.class);
                log.info("print:{}", print);
            }
            if (print) {
                log.info("success：{}", valueParser.parse(point, logging::successMsg, proceed, null, String.class));
            }
        } catch (Exception e) {
            if (print) {
                log.info("error：{}", valueParser.parse(point, logging::failMsg, null, e.getMessage(), String.class));
            }
            throw e;
        }
        return proceed;
    }
}


